import request from '../request'
import type { ApiResponse } from '../types'
import { rsaEncryptBase64, sha256Hex } from '@/utils/crypto'
import type { User } from '@/types/User'

// 登录
type LoginPayload = { email: string; password: string; enc?: string }

export async function loginApi(data: { email: string; password: string }) {
  const payload: LoginPayload = { ...data }
  const envVars = import.meta.env
  const pem = (envVars?.VITE_LOGIN_RSA_PUBLIC_KEY as string | undefined)
  const mode = String(envVars?.VITE_LOGIN_PASSWORD_MODE || '').toLowerCase()
  const isDev = !!envVars?.DEV
  const debug = isDev && String(envVars?.VITE_LOGIN_DEBUG || '') === '1'
  const log = (...args: unknown[]) => { if (debug) { /* eslint-disable no-console */ console.debug('[loginApi]', ...args) /* eslint-enable no-console */ } }
  const hasPem = !!(pem && pem.trim())
  const rsaPreferred = hasPem && mode !== 'sha256' && mode !== 'none'
  log('mode:', mode || '(none)', 'rsaPreferred:', rsaPreferred)

  if (rsaPreferred) {
    try {
      const encPwd = await rsaEncryptBase64(data.password, pem as string)
      payload.password = encPwd
      payload.enc = 'rsa-oaep-256'
      log('RSA success')
      return request<null>({
        url: '/auth/login',
        method: 'POST',
        data: payload,
        headers: { 'X-Pwd-Enc': 'rsa-oaep-256' },
      })
    } catch (e) {
      log('RSA failed -> throw', e)
      throw new Error('RSA encryption failed')
    }
  }

  if (mode === 'sha256') {
    try {
      const digest = await sha256Hex(data.password)
      payload.password = digest
      payload.enc = 'sha-256'
      log('SHA-256 success')
      return request<null>({
        url: '/auth/login',
        method: 'POST',
        data: payload,
        headers: { 'X-Pwd-Enc': 'sha-256' },
      })
    } catch (e) {
      log('SHA-256 failed -> plaintext fallback', e)
    }
  }

  log('plaintext path')
  return request<null>({
    url: '/auth/login',
    method: 'POST',
    data: payload,
  })
}

// 获取用户信息
export async function getUserInfo(data:{token: string}) {
  return request<User>({
    url: '/auth/info',
    method: 'GET',
    params: data
  })
}

// 更新用户信息
export async function updateUserInfo(data: Partial<User>) {
  return request<ApiResponse<User>>({
    url: '/auth/update',
    method: 'POST',
    data
  })
}

export async function resetPasswordApi(data: { email: string; verificationCode: string; newPassword: string; }) {
    return request<null>({
        url: '/auth/reset-password',
        method: 'POST',
        data
    })
}